const express = require('express');
const router = express.Router();
const AuthController = require('../../controllers/AuthController');
const { authenticateJWT, authorizeAdmin } = require('../../middleware/auth');

/**
 * 认证相关路由
 * 提供用户登录、注册、令牌管理等API接口
 */

// 公开路由（无需认证）

/**
 * @route   POST /api/auth/login
 * @desc    用户登录
 * @access  Public
 */
router.post('/login', AuthController.login);

/**
 * @route   POST /api/auth/register
 * @desc    用户注册
 * @access  Public
 */
router.post('/register', AuthController.register);

/**
 * @route   POST /api/auth/refresh
 * @desc    刷新令牌
 * @access  Public (需要有效的刷新令牌)
 */
router.post('/refresh', AuthController.refreshToken);

/**
 * @route   POST /api/auth/request-reset
 * @desc    请求重置密码
 * @access  Public
 */
router.post('/request-reset', AuthController.requestPasswordReset);

/**
 * @route   POST /api/auth/request-password-reset
 * @desc    请求重置密码（备用路径，与文档保持一致）
 * @access  Public
 */
router.post('/request-password-reset', AuthController.requestPasswordReset);

/**
 * @route   POST /api/auth/reset-password
 * @desc    重置密码
 * @access  Public (需要有效的重置令牌)
 */
router.post('/reset-password', AuthController.resetPassword);

// 需要认证的路由

/**
 * @route   POST /api/auth/logout
 * @desc    用户登出
 * @access  Private
 */
router.post('/logout', authenticateJWT, AuthController.logout);

/**
 * @route   GET /api/auth/me
 * @desc    获取当前用户信息
 * @access  Private
 */
router.get('/me', authenticateJWT, AuthController.getCurrentUser);

/**
 * @route   PUT /api/auth/password
 * @desc    修改密码
 * @access  Private
 */
router.put('/password', authenticateJWT, AuthController.changePassword);

/**
 * @route   PUT /api/auth/profile
 * @desc    更新用户信息
 * @access  Private
 */
router.put('/profile', authenticateJWT, AuthController.updateProfile);

// 管理员路由（需要管理员权限）

/**
 * @route   GET /api/auth/users
 * @desc    获取所有用户列表（管理员）
 * @access  Private (Admin)
 */
router.get('/users', authenticateJWT, authorizeAdmin, async (req, res, next) => {
  try {
    const User = require('../../models/User');
    const users = await User.findAll({
      attributes: {
        exclude: ['password', 'loginAttempts', 'lockUntil', 'deletedAt']
      }
    });
    
    res.status(200).json({
      success: true,
      message: '获取用户列表成功',
      data: {
        users: users.map(user => user.toJSON())
      }
    });
  } catch (error) {
    next(error);
  }
});

/**
 * @route   PUT /api/auth/users/:id/status
 * @desc    更新用户状态（管理员）
 * @access  Private (Admin)
 */
router.put('/users/:id/status', authenticateJWT, authorizeAdmin, async (req, res, next) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    if (status === undefined || ![0, 1].includes(status)) {
      return res.status(400).json({
        success: false,
        message: '状态值无效，必须为0或1'
      });
    }
    
    const User = require('../../models/User');
    const user = await User.findByPk(id);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    await user.update({ status });
    
    res.status(200).json({
      success: true,
      message: '用户状态更新成功',
      data: {
        user: {
          id: user.id,
          username: user.username,
          status: user.status
        }
      }
    });
  } catch (error) {
    next(error);
  }
});

module.exports = router;

// 导出到全局（如果需要）
if (!global.authRoutes) {
  global.authRoutes = router;
}